import com.entity.User;
import com.util.DatabaseUtil;
import org.junit.Test;

import java.sql.*;

import static org.junit.Assert.*;

public class UserCRUDTest {

    @Test
    public void createTable() {
        DatabaseUtil.createTestTable();
    }

    @Test
    public void createData() {
        String TABLE_NAME = DatabaseUtil.getTableName();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DatabaseUtil.getConnection();
            User testUser = new User("张三",  25, "zhangsan@example.com");
            // 插入SQL
            String insertSQL = "INSERT INTO " + TABLE_NAME +
                    " (name, age, email) VALUES (?, ?, ?)";

            statement = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
            statement.setString(1, testUser.getName());
            statement.setInt(2, testUser.getAge());
            statement.setString(3, testUser.getEmail());

            // 执行插入
            int affectedRows = statement.executeUpdate();
            assertEquals("应该插入1条记录", 1, affectedRows);

            // 获取生成的主键
            resultSet = statement.getGeneratedKeys();
            assertTrue("应该生成主键", resultSet.next());
            int generatedId = resultSet.getInt(1);
            testUser.setId(generatedId);

            System.out.println("✅ 用户插入成功！ID: " + generatedId);
            System.out.println("插入的用户信息: " + testUser);
        } catch (Exception e){
            fail("插入用户失败: " + e.getMessage());
        } finally {
            DatabaseUtil.closeAll(connection, statement, resultSet);
        }
    }

}
